package com.jy.wms.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.BaseService;
import com.jy.wms.common.base.BaseSessionInfo;
import com.jy.wms.common.base.ServiceException;
import com.jy.wms.common.base.SucessException;
import com.jy.wms.dao.*;
import com.jy.wms.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName: WmsRejectedService.java
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author Jane
 * @Date Tue Jan 16 17:18:20 CST 2018
 */

@Service
public class WmsRejectedService extends BaseService<WmsRejectedMapper,WmsRejected> {

    @Autowired
    private WmsRejectedDetailedMapper wmsRejectedDetailedMapper;
    @Autowired
    private WmsEstimatedArrivalOrderMapper wmsEstimatedArrivalOrderMapper;
    @Autowired
    private WmsEstimatedArrivalOrderDetailedMapper wmsEstimatedArrivalOrderDetailedMapper;
    @Autowired
    private WmsPackingDetailedMapper wmsPackingDetailedMapper;


    @BaseServiceDescribe(moduleName = "退货单",btnName = "查询类型为入库的收发类别")
    public List<WmsOwnerOrdertype> getOrderTypeCk(HttpSession session){
        UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        List<SysHz> hz = (List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
        String hzid = "";
        if(hz.size()>0){
            hzid = hz.get(0).getHzid();
        }
        return dao.getOrderTypeCk(hzid);
    }

    /**
     * 插入一条记录
     * @param entity 实体对象
     * @return int
     */
    @BaseServiceDescribe(moduleName = "退货单",btnName = "保存退货单信息")
    @Transactional
    public void baseInsert(WmsRejected entity, HttpSession session)throws ServiceException,SucessException {
        UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
        //承接传入的退货单信息
        List<WmsRejectedDetailed> wmsRejectedDetailedList = entity.getWmsRejectedDetailedList();
        if(wmsRejectedDetailedList.size()==0){
            throw new ServiceException("无退货订单信息");
        }
        //获取退货单明细，并且去掉退货数量等于0 的明细
        List<WmsRejectedDetailed> list = new ArrayList<>();
        //获取所有不重复的供应商
        HashSet<String> gysids = new HashSet();
        for (WmsRejectedDetailed wmsRejectedDetailed : wmsRejectedDetailedList) {
            if(Integer.valueOf(wmsRejectedDetailed.getThsl()) > 0 ){
                gysids.add(wmsRejectedDetailed.getGysid());
                list.add(wmsRejectedDetailed);
            }

        }
        //根据供应商拆分数据
        List<WmsRejectedDetailed> listGys = new ArrayList<WmsRejectedDetailed>();
        //记录拆分的货品编号、批次、生产日期
        List<WmsRejectedDetailed> split = new ArrayList<WmsRejectedDetailed>();
        //保存预期到货通知单信息
        WmsEstimatedArrivalOrder wmsEstimatedArrivalOrder;
        //预期到货通知单明细
        WmsEstimatedArrivalOrderDetailed wmsEstimatedArrivalOrderDetailed;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        //遍历供应商 每个供应商生成一条ASN订单
        for (String gysid : gysids) {
            for (WmsRejectedDetailed wmsRejectedDetailed : list) {
                if(wmsRejectedDetailed.getGysid().equals(gysid)){
                    listGys.add(wmsRejectedDetailed);
                }
            }
            //判断是否需要加入
            boolean type;
            //遍历当前供应商 对应的明细信息 根据 货品编号、批次、生产日期 完全相同  如果相同则合并退货数量
            for (WmsRejectedDetailed listGy : listGys) {
                //判断是否需要加入
                type = true;
                if(split.size()>0){
                    //创建一条临时退货信息
                    List<WmsRejectedDetailed> splitNow = new ArrayList<WmsRejectedDetailed>();
                    for (WmsRejectedDetailed listGySplit : split) {
                        if(Integer.valueOf(listGySplit.getThsl()) > 0){
                            if (listGySplit.getHpbh().equals(listGy.getHpbh()) && listGySplit.getPc().equals(listGy.getPc()) && listGySplit.getScrq().equals(listGy.getScrq())) {
                                //如果 货品编号、批次、生产日期 完全相同 则相加
                                listGy.setThsl(String.valueOf(Integer.valueOf(listGySplit.getThsl()) + Integer.valueOf(listGy.getThsl())));
                                type = false;
                            }
                        }
                    }
                    if(type){
                        split.add(listGy);
                    }
                }else{
                    split.add(listGy);
                }
            }
            wmsEstimatedArrivalOrder = new WmsEstimatedArrivalOrder();
            wmsEstimatedArrivalOrder.setId(UUIDUtils.uuid());
            wmsEstimatedArrivalOrder.setGysid(gysid);
            if(hz.size()>0){
                wmsEstimatedArrivalOrder.setHzid(hz.get(0).getHzid());
            }
            String asnbh = df.format(new Date())+ Integer.toString((int)(Math.random()*9+1)*1000);
            while (wmsEstimatedArrivalOrderMapper.getCountByAsnbh(asnbh) > 0 ){
                asnbh = df.format(new Date())+ Integer.toString((int)(Math.random()*9+1)*1000);
            }
            String time = df.format(new Date());
            wmsEstimatedArrivalOrder.setAsnbh(asnbh);
            wmsEstimatedArrivalOrder.setAsnlx(entity.getAsnLxid());
            wmsEstimatedArrivalOrder.setZdr(userinfo.getUser().getName());
            wmsEstimatedArrivalOrder.setBz(entity.getBz()==null?"":entity.getBz());
            wmsEstimatedArrivalOrder.setCjsj(time);
            wmsEstimatedArrivalOrder.setYjdhsjks(time);
            wmsEstimatedArrivalOrder.setYjdhsjjs(time);
            wmsEstimatedArrivalOrder.setShzt("1");//审核状态 0 未审核  1审核
            wmsEstimatedArrivalOrder.setCkid(String.valueOf(userinfo.getUser().getOrgId().get(0)));
            List<WmsEstimatedArrivalOrderDetailed> wmsEstimatedArrivalOrderDetailedList = new ArrayList<WmsEstimatedArrivalOrderDetailed>();
            for (WmsRejectedDetailed rejectedDetailed : split) {
                Integer kythsl = dao.getThsl(rejectedDetailed.getFyddmxid());
                if(kythsl >= Integer.valueOf(rejectedDetailed.getThsl())){
                    //更新发运订单明细退货状态
                    if(kythsl.equals(Integer.valueOf(rejectedDetailed.getThsl()))){
                        dao.updateWmsshipmentOrderDetailed(rejectedDetailed.getFyddmxid(),"2");
                    }else{
                        dao.updateWmsshipmentOrderDetailed(rejectedDetailed.getFyddmxid(),"1");
                    }
                    //更新发运订单退货状态
                    dao.updateWmsshipmentOrder(rejectedDetailed.getFyddid(),dao.getCountByThzt(rejectedDetailed.getFyddid()).toString());
                    wmsEstimatedArrivalOrderDetailed = new WmsEstimatedArrivalOrderDetailed();
                    wmsEstimatedArrivalOrderDetailed.setId(UUIDUtils.uuid());
                    wmsEstimatedArrivalOrderDetailed.setSsyqdid(wmsEstimatedArrivalOrder.getId());
                    wmsEstimatedArrivalOrderDetailed.setHpid(rejectedDetailed.getHpid());
                    wmsEstimatedArrivalOrderDetailed.setYqsl(rejectedDetailed.getThsl());
                    //货品包装
                    WmsPacking wmsPacking = dao.getPack(rejectedDetailed.getHpid());
                    //货品包装明细 按照类型正序排序
                    List<WmsPackingDetailed> wmsPackingDetailedList = wmsPackingDetailedMapper.baseSelectByBzid(wmsPacking.getId());
                    Double je = Double.valueOf(rejectedDetailed.getThsl()) * Double.valueOf(wmsPackingDetailedList.get(0).getJe());
                    wmsEstimatedArrivalOrderDetailed.setJe(new BigDecimal(je));
                    wmsEstimatedArrivalOrderDetailed.setHppc(rejectedDetailed.getPc());
                    wmsEstimatedArrivalOrderDetailed.setScrq(rejectedDetailed.getScrq());
                    wmsEstimatedArrivalOrderDetailed.setSxrq(rejectedDetailed.getSxrq());
                    wmsEstimatedArrivalOrderDetailed.setZdwid(wmsPackingDetailedList.get(0).getId());
                    Integer yqsl = Integer.valueOf(rejectedDetailed.getThsl());
                    StringBuffer yqxsl = new StringBuffer("");
                    yqxsl.append((yqsl/ Integer.valueOf(wmsPackingDetailedList.get(2).getZdwsl()))+"箱");
                    yqxsl.append((yqsl% Integer.valueOf(wmsPackingDetailedList.get(2).getZdwsl()))+"件");
                    wmsEstimatedArrivalOrderDetailed.setYqxsl(yqxsl.toString());
                    wmsEstimatedArrivalOrderDetailed.setDycgmxid("0");
                    wmsEstimatedArrivalOrderDetailed.setBz(entity.getBz()==null?"":entity.getBz());
                    if(hz.size()>0){
                        wmsEstimatedArrivalOrder.setHzid(hz.get(0).getHzid());
                    }

                    wmsEstimatedArrivalOrderDetailed.setCkid(String.valueOf(userinfo.getUser().getOrgId().get(0)));
                    wmsEstimatedArrivalOrderDetailedList.add(wmsEstimatedArrivalOrderDetailed);
                }else{
                    throw new ServiceException("退货数量不足");
                }
            }
            //保存预期到货通知单信息
            wmsEstimatedArrivalOrderMapper.baseInsertSelective(wmsEstimatedArrivalOrder);
            //保存预期到货通知单明细信息
            wmsEstimatedArrivalOrderDetailedMapper.baseInsertAll(wmsEstimatedArrivalOrderDetailedList);
            //保存退货单信息
            entity.setId(UUIDUtils.uuid());
            entity.setCkid(String.valueOf(userinfo.getUser().getOrgId().get(0)));
            String thdh = "th"+ df.format(new Date())+ Integer.toString((int)(Math.random()*9+1)*1000);
            while (dao.getCountByThdh(thdh) > 0 ){
                thdh = "th"+ df.format(new Date())+ Integer.toString((int)(Math.random()*9+1)*1000);
            }
            entity.setThdh(thdh);
            for (WmsRejectedDetailed wmsRejectedDetailed : list) {
                if(wmsRejectedDetailed.getGysid().equals(gysid)){
                    wmsRejectedDetailed.setId(UUIDUtils.uuid());
                    wmsRejectedDetailed.setThdid(entity.getId());
                    wmsRejectedDetailed.setRkdh(wmsEstimatedArrivalOrder.getAsnbh());
                }
            }
        }
        //保存退货单
        entity.setXgsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
        dao.baseInsertSelective( entity );
        //保存退货单明细信息
        wmsRejectedDetailedMapper.baseInsertAll(list);
        throw new SucessException("保存退货单成功");
    }

    /**
     * 插入一条记录（匹配有值的字段）
     * @param entity 实体对象
     * @return int
     */
    public Integer baseInsertSelective(WmsRejected entity){
        return dao.baseInsertSelective( entity);
    }

    /**
     * 删除（根据主键ID删除）
     * @param id 主键
     * @return int
     */
    public Integer baseDeleteByPrimaryKey(String id){
        return dao.baseDeleteByPrimaryKey( id);
    }

    /**
     * 删除（根据ID 批量删除）
     * @param idList 主键ID列表
     * @return int
     */
    public Integer baseDeleteBathPrimaryKeys(List<String> idList){
        return dao.baseDeleteBathPrimaryKeys( idList );
    }

    /**
     * 分页查询SO
     * @return Page<WmsRejected>
     */
    @BaseServiceDescribe(moduleName = "退货单",btnName = "选择发运订单列表")
    public Page<Map<String,Object>> getSoPage(Map<String,Object> map)throws Exception {
        try {
            PageHelper.startPage(Integer.valueOf(map.get("page").toString()), Integer.valueOf(map.get("rows").toString()));
            return (Page<Map<String,Object>>)dao.getSo(map);
        } catch (Exception e) {
            throw new ServiceException("分页查询SO",e);
        }
    }

    /**
     * 分页查询
     * @param entity 实体
     * @return Page<WmsRejected>
     */
    @BaseServiceDescribe(moduleName = "退货单",btnName = "查询退货单列表信息")
    public Page<WmsRejected> baseSelectPage(WmsRejected entity )throws Exception {
        try {
            PageHelper.startPage(entity.getPage(),entity.getRows());
            return (Page<WmsRejected>)dao.baseSelectPage( entity );
        } catch (Exception e) {
            throw new ServiceException("查询退货单列表信息",e);
        }
    }

    /**
     * 查询（根据主键ID查询）
     * @param id 主键ID
     * @return WmsRejected
     */
    public WmsRejected baseSelectByPrimaryKey(String id ){
        return dao.baseSelectByPrimaryKey( id );
    }

    /**
     * 查询（根据ID 批量查询）
     * @param idList 主键ID列表
     * @return list
     */
    public Integer baseSelectBathPrimaryKeys(List<WmsRejected> idList ){
        return dao.baseSelectBathPrimaryKeys( idList );
    }

    /**
     *修改 （匹配有值的字段）
     * @param entity 主键ID列表
     * @return int
     */
    public Integer baseUpdateByPrimaryKeySelective(WmsRejected entity){
        return dao.baseUpdateByPrimaryKeySelective( entity);
    }

    /**
     *修改（根据主键ID修改）
     * @param entity 主键ID列表
     * @return int
     */
    public Integer baseUpdateByPrimaryKey(WmsRejected entity){
        return dao.baseUpdateByPrimaryKey( entity);
    }
}
